import type { MenuNode } from "@/types/menu";
import { queryTreeList } from "@/api";

/**
 * 获取当前路由所属的 type="0" 菜单组的全部子菜单（即同级功能列表）
 * 用途：生成功能标签页、子模块导航、权限入口等
 */
export async function getPermissionsByRoute(name): Promise<MenuNode[]> {
  const menuTree = await queryTreeList('menu');
  const currentRouteName = name as string | undefined;

  if (!currentRouteName) return [];

  let targetPath: MenuNode[] | null = null;

  // 深度优先搜索，记录路径
  function dfs(nodes: MenuNode[], path: MenuNode[]): boolean {
    for (const node of nodes) {
      const currentPath = [...path, node];

      if (node.id === currentRouteName || node.name === currentRouteName) {
        targetPath = currentPath;
        return true;
      }

      if (node.children?.length) {
        if (dfs(node.children, currentPath)) {
          return true;
        }
      }
    }
    return false;
  }

  dfs(menuTree, []);

  if (!targetPath) return [];

  // 从当前节点向上找第一个 type === "0" 的祖先
  for (let i = targetPath.length - 1; i >= 0; i--) {
    const ancestor = targetPath[i];
    if (ancestor.type === "0") {
      return ancestor.children?.length ? [...ancestor.children] : [];
    }
  }

  return []; // 没找到 type="0" 的父组
}